<template>
 <div class="t-send-code">
   <Button v-if="num >= 60" @click="sendCode" :loading="loading" class="btn-code" size="large" slot="append">
     {{$t('user.getVerificationCode')}}
   </Button>
   <Button v-else class="btn-code" size="large" slot="append">
     {{num}} S
   </Button>
 </div>
</template>

<script>
import {sendCodeByEmail} from "@/api/user";

export default {
  name: "t-send-code",
  props: {
    email: String,
    type: [String, Number]
  },
  data() {
    return {
      num: 60,
      timer: '',
      loading: false,
    }
  },
  methods: {
    sendCode() {
      // 发送验证码
      if(this.timer) {
        clearInterval(this.timer);
        this.timer = '';
      }
      this.loading = true;
      sendCodeByEmail({
        email: this.email,
        type: this.type
      }).then((res)=>{
        this.loading = false;
        this.countdown();
      }).catch(()=>{
        this.loading = false;
      })
    },
    countdown() {
      // 倒计时
      this.timer = setInterval(()=>{
        if (this.num <= 0) {
          clearInterval(this.timer);
          this.timer = '';
          this.num = 60;
        } else {
          this.num = this.num - 1;
        }
      }, 1000)
    }
  }
}
</script>

<style scoped lang="less">
.t-send-code {
  .btn-code {
    font-size: 14px;
  }
}
</style>